package controllers.category;

import models.Category;
import play.data.Form;
import play.mvc.Controller;
import play.mvc.Result;

import com.avaje.ebean.Ebean;

import controllers.user.UserController;

public class CategoryController extends Controller {

	public static Form<Category> form = form(Category.class);

	public static Result list() {
		if (UserController.getCurrentUser().getPriv("worker")) {
			return ok(views.html.category.list.render(
					Category.rootCategories(), form, ""));
		}
		return redirect(controllers.user.routes.UserController.logIn());
	}

	public static Result create() {
		Form<Category> filledForm = form.bindFromRequest();

		if (filledForm.hasErrors()) {
			return badRequest(views.html.category.list.render(
					Category.rootCategories(), form, "error"));

		} else { // filledForm.data().get("parent_id")
			Category category = filledForm.get();

			try {
				category.setParent(Ebean.find(Category.class, filledForm.data()
						.get("parent_id")));
			} catch (NumberFormatException e) {
				category.setParent(null);
			}

			try {
				Category.create(category);
			} catch (Exception e) {
				return ok(views.html.category.list.render(
						Category.rootCategories(), form,
						"*entry already exists"));
			}
		}
		return list();
	}

	public static Result delete(Long id) {
		Category.delete(id);
		return list();
	}
}